# -*- encoding:utf-8 -*-
import urllib
import simplejson
import re

tbodyregex = ur"<tbody(\s|\S)*?/tbody>"
trregex = ur"<tr(\s|\S)*?/tr>"

def search(keyword):
    """
    @param keyword keyword in encoding utf-8?
    @return music list with corresponding info
    """
    s = getSearchHtml(keyword)
    dic = {}
    dic['tracks'] = getTrackResults(s)
    dic['artists'] = getArtistResults(s)
    dic['albums'] = getAlbumResults(s)
    return dic

def getTrackResults(htmltext):
    """
    @param htmltext the html text
    @return track result list
    """
    tracklistregex = ur"<table class=\"track_list\"(\s|\S)*?table>"
    trackstr = ""
    tracklistsearch = re.search(tracklistregex,htmltext)
    if tracklistsearch:
        trackstr = htmltext[tracklistsearch.start():tracklistsearch.end()]
    else:
        return []

    tbodysearch = re.search(tbodyregex,trackstr)
    tbodystr = ""
    if tbodysearch:
        tbodystr = trackstr[tbodysearch.start():tbodysearch.end()]
    else:
        return []

    result = []
    for trmatch in re.finditer(trregex,tbodystr):
        tmpdic = {}
        trstr = tbodystr[trmatch.start():trmatch.end()]
        
        #songid,songname
        songregex = ur"/song/(\s|\S)*?>"
        songsearch = re.search(songregex,trstr)
        if songsearch:
            songstr = trstr[songsearch.start():songsearch.end()]
        else:
            raise Exception("song:file format error")
        songid = songstr[6:songstr.index("\"",6)]
        songname = songstr[songstr.index("title")+7:len(songstr)-2]
        #songnameindex = songstr.index("title")+7
        #songname = songstr[songnameindex:song.index("\"",songnameindex)]
        tmpdic['songid'] = songid
        tmpdic['songname'] = songname
        
        #artistid,artistname
        artistregex = ur"/artist/(\s|\S)*?>"
        artistsearch = re.search(artistregex,trstr)
        if artistsearch:
            artiststr = trstr[artistsearch.start():artistsearch.end()]
        else:
            raise Exception("artist:file format error")
        artistid = artiststr[8:artiststr.index("\"",8)]
        artistname = artiststr[artiststr.index("title")+7:len(artiststr)-2]
        tmpdic["artistid"] = artistid
        tmpdic["artistname"] = artistname

        #albumid,albumname
        albumregex = ur"/album/(\s|\S)*?>"
        albumsearch = re.search(albumregex,trstr)
        if albumsearch:
            albumstr = trstr[albumsearch.start():albumsearch.end()]
        else:
            raise Exception("album : file format error")
        albumid = albumstr[7:albumstr.index("\"",7)]
        albumname = albumstr[albumstr.index("title")+7:len(albumstr)-2]
        tmpdic['albumid'] = albumid
        tmpdic['albumname'] = albumname
        
        result.append(tmpdic)
    return result


    

def getArtistResults(htmltext):
    """
    @param htmltext
    @return artist results list
    """

def getAlbumResults(htmltext):
    """
    @param htmltext
    @return album results list
    """

def getSearchHtml(query):
    theurl = "http://www.xiami.com/search?key="+str(query)+"&pos=1"
    l = urllib.urlopen(theurl)
    s = l.read()
    l.close()
    return s

if __name__ == "__main__":
    print search(u"蓝色生死恋".encode("utf-8"))
